const ThemeColorReplacer = require('webpack-theme-color-replacer');
const { getThemeColors, modifyVars } = require('./src/util/theme');

const path = require('path');

const isProd = process.env.NODE_ENV === 'production';
const publicPath =
  process.env.NODE_MODE === 'pro' ? '/office-prepro-web/info-release' : '/info-release';
console.log(99, publicPath);
// 判断打包时运行一个查看项目大小的服务
const IS_OPEN_PREVIEW_PLUGIN = process.argv.slice(-1)[0] === '--IS_OPEN_PREVIEW_PLUGIN';

function resolve(dir) {
  return path.join(__dirname, dir);
}

function previewBuild() {
  const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
  return new BundleAnalyzerPlugin();
}

const assetsCDN = {
  externals: {
    axios: 'axios',
    qs: 'Qs'
  },
  css: [],
  js: [
    // 'https://cdn.staticfile.org/axios/0.18.0/axios.min.js',
    // 'https://cdn.bootcss.com/qs/6.7.0/qs.min.js'
  ]
};

function openGzip() {
  const CompressionWebpackPlugin = require('compression-webpack-plugin');
  const compress = new CompressionWebpackPlugin({
    filename: '[path].gz[query]',
    threshold: 10240,
    minRatio: 0.8,
    test: new RegExp('\\.(' + ['js', 'css'].join('|') + ')$'),
    deleteOriginalAssets: false
  });
  return compress;
}
// http://192.168.91.45:8834 张衡
// http://192.168.90.163:8301 杨振
// http://192.168.90.101:8834/ 志波
// http://192.168.90.50:8025/
module.exports = {
  productionSourceMap: false,
  publicPath: publicPath,
  devServer: {
    hot: false,
    disableHostCheck: true,
    port: 9005,
    open: true,
    overlay: {
      warnings: false,
      errors: true
    },
    headers: {
      'Access-Control-Allow-Origin': '*'
    },
    proxy: {
      '/api': {
        // target: 'http://192.168.80.130:8824/',
        target: process.env.VUE_APP_REQUEST_BASE_URL,
        ws: true,
        changeOrigin: true,
        pathRewrite: {
          '^/api': ''
        }
      },
      '/west': {
        target: 'https://saaspre.jnshiyanqu.cn/gateway/',
        ws: true,
        changeOrigin: true,
        pathRewrite: {
          '^/west': ''
        }
      }
    }
  },
  pluginOptions: {
    'style-resources-loader': {
      preProcessor: 'less',
      patterns: [resolve('src/assets/styles/base/variables.less')]
    }
  },
  css: {
    // 是否分离css true:分离css，会造成css无法热更新，false：会把css打包进js中，js一更新css自然更新
    extract: process.env.NODE_ENV !== 'development',
    sourceMap: false,
    loaderOptions: {
      less: {
        lessOptions: {
          modifyVars: modifyVars(), // 初始化定制主题
          // modifyVars: {
          //   // ...getThemeVariables(),
          //   'ant-prefix': 'micro-ant',
          //   'primary-color': '#d6aa56',
          //   'border-radius-base': '5px',
          //   'btn-border-radius-base': '5px',
          //   'border-radius-sm': '2px',
          //   'table-border-radius-base': '2px'
          // },
          javascriptEnabled: true
        }
      }
    }
  },
  configureWebpack() {
    const config = {
      plugins: [
        openGzip(),
        new ThemeColorReplacer({
          fileName: 'css/theme-colors-[contenthash:8].css', // 输出css文件名，支持[contenthash]和[hash]。
          matchColors: getThemeColors(), // 用于提取 css 文件的颜色数组，支持 rgb 和 hsl。
          injectCss: true // 将 css 文本注入 js 文件，不再需要下载 `theme-colors-xxx.css`
        })
      ]
    };
    if (IS_OPEN_PREVIEW_PLUGIN) {
      config.plugins.push(previewBuild());
    }
    // if (isProd) {
    //   config.externals = assetsCDN.externals;
    // }
    return config;
  },
  chainWebpack(config) {
    // if (isProd) {
    //   config.plugin('html').tap(args => {
    //     args[0].cdn = assetsCDN;
    //     return args;
    //   });
    // }
    if (isProd) {
      config.optimization.splitChunks({
        chunks: 'all',
        maxInitialRequests: Infinity,
        minSize: 300000, // 依赖包超过300000bit将被单独打包
        automaticNameDelimiter: '-',
        cacheGroups: {
          vendor: {
            test: /[\\/]node_modules[\\/]/,
            name(module) {
              const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1];
              return `chunk.${packageName.replace('@', '')}`;
            },
            priority: 10
          }
        }
      });
    }
    config.plugin('html').tap(args => {
      args[0].NODE_ENV = process.env.NODE_ENV;
      args[0].HUAWEI_SITE_MONITOR_APPID = process.env.VUE_APP_HUAWEI_SITE_MONITOR_APPID;
      return args;
    });
    config.module
      .rule('vue')
      .use('vue-loader')
      .tap(options => {
        options.compilerOptions = {
          ...(options.compilerOptions || {}),
          isCustomElement: tag => /^micro-app/.test(tag)
        };
        return options;
      });
    // svg依赖的配置
    handleSvgIcon(config);
  }
};

// svg依赖的配置
const handleSvgIcon = config => {
  config.module.rule('svg').exclude.add(resolve('src/assets/icons/svg')).end();
  config.module
    .rule('icons')
    .test(/\.svg$/)
    .include.add(resolve('src/assets/icons/svg'))
    .end()
    .use('svg-sprite-loader')
    .loader('svg-sprite-loader')
    .options({
      symbolId: 'custom-icon-[name]'
    })
    .end()
    .before('svg-sprite-loader')
    .use('svgo-loader')
    .loader('svgo-loader')
    .options({
      plugins: [
        {
          name: 'preset-default',
          params: {
            overrides: {}
          }
        },
        {
          name: 'removeAttrs',
          params: {
            attrs: '(fill|fill-rule|clip-rule)'
          }
        },
        {
          name: 'addAttributesToSVGElement',
          params: {
            attributes: [{ fill: 'currentColor' }]
          }
        }
      ]
    });
};
